package com.situ.springboot.controller;

import com.situ.springboot.pojo.Dept;
import com.situ.springboot.pojo.User;
import com.situ.springboot.service.IDeptService;
import com.situ.springboot.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IDeptService deptService;


    // http://localhost:3306/user/list
    @RequestMapping("/list")
    public String selectAll(Model model) {
        System.out.println("UserController.selectAll");

        //查找数据库
        List<User> list = userService.selectAll();
        model.addAttribute("list", list);
        //跳转到页面展示
        return "/user/user_list";
    }

    @RequestMapping("/deleteById")
    public String deleteById(Integer id) {
        userService.deleteById(id);

        //删除完了之后，查找最新的数据
        return "redirect:/user/list";
    }

    @RequestMapping("/toAdd")
    public String toAdd(Model model) {
        List<Dept> list = deptService.selectAll();
        model.addAttribute("list", list);
        return "/user/user_add";
    }

    @RequestMapping("/add")
    public String add(User user) {
        userService.add(user);

        //添加完了之后，查找最新的数据
        return "redirect:/user/list";
    }

    @RequestMapping("/toUpdate")
    public String toUpdate(Integer id, Model model) {
        User user = userService.selectById(id);
        model.addAttribute("user", user);
        List<Dept> list = deptService.selectAll();
        model.addAttribute("list", list);
        return "/user/user_update";
    }

    @RequestMapping("/update")
    public String update(User user) {
        System.out.println("user: " + user);
        userService.update(user);

        //更新完了之后，查找最新的数据
        return "redirect:/user/list";
    }

    // /user/toLogin
    @RequestMapping("/toLogin")
    public String toLogin() {
        return "/user/user_login";
    }

    @RequestMapping("/login")
    public String login(String username, String password, Model model, HttpSession session) {
        User user = userService.login(username, password);
        //根据用户名和密码查找
        //如果user==null，代表登录失败，用户名密码错误
        //如果user!=null 代表登录成功
        if (user == null) {
            model.addAttribute("msg", "用户名密码错误");
            return "/user/user_login";
        } else {//登录成功
            session.setAttribute("user", user);
            return "redirect:/";
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/user/toLogin";
    }
}
